//
//  SmallP_ex_array.swift
//  SmallPrograms
//
//  Created by mac on 2022/11/14.
//

import UIKit

extension Array {
    
    //TODO: - 随机打乱一组数据
    func randomInfos() -> [Element] {
        guard !self.isEmpty else { return self }
        var data: [Element] = self
        for i in 1..<self.count {
            let index: Int = Int(arc4random()) % i
            if index != i {
                data.swapAt(i, index)
            }
        }
        return data
    }
    
}

extension Array where Element: Equatable {
    
    //TODO: - 删除 item
    func remove(_ object: Element) -> [Element] {
        self.filter({ $0 != object })
    }
    
    //TODO: - 过滤重复 item
    /// 过滤重复 item
    func filter(repeat items: [Element]) -> [Element] {
        var elements = [Element]()
        self.forEach { element in
            if !items.contains(where: { $0 == element }) {
                elements.append(element)
            }
        }
        return elements
    }
    /// 去重
    func uniqued<H: Hashable>(_ filter: (Element) -> H) -> [Element] {
        var result = [Element]()
        var map = [H: Element]()
        for ele in self {
            let key = filter(ele)
            if map[key] == nil {
                map[key] = ele
                result.append(ele)
            }
        }
        return result
    }
    
    func filterDuplicates<E: Equatable>(_ filter: (Element) -> E) -> [Element] {
        var result = [Element]()
        for value in self {
            let key = filter(value)
            if !result.map({filter($0)}).contains(key) {
                result.append(value)
            }
        }
        return result
    }
}
